//
//  YH_IPubHistoryViewController.m
//  YinHang
//
//  Created by 123 on 14-6-23.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_IPubHistoryViewController.h"
#import "IPubHistoryTableViewCell.h"
#import "YH_NewsDetailViewController.h"

@interface YH_IPubHistoryViewController ()
{
    NSInteger selectedIndex;
    
    NewsListService *nls_;
    
    NSInteger btnTag;//点编辑或删除按钮时用到
    
    ASIFormDataRequest *editRequest_;//编辑请求
    ASIFormDataRequest *delRequest_;//删除请求
}
@end

@implementation YH_IPubHistoryViewController

/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
- (void)dealloc
{
    nls_ = nil;
    NSLog(@"MJTableViewController--dealloc---");
}

#pragma mark - 初始化

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationController.navigationBarHidden=NO;
    self.navigationItem.title = @"引航网";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }

    
    // 加载选项卡
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"新闻", @"人才", @"视频", @"产品", @"图片",@"服务"]];
    selectedIndex = 0;
    
    [segmentedControl setIndexChangeBlock:^(NSUInteger index) {
        [_tableView headerEndRefreshing];
        
        selectedIndex = index;
        
        // 切换页面 每次一进入页面就下拉刷新
        [_tableView headerBeginRefreshing];
    }];
    [segmentedControl setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35)];
    [self.view addSubview:segmentedControl];
    
    
    // 屏幕适配
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.bounds.size.width, self.view.bounds.size.height-_tableView.frame.origin.y-15);
    
    _tableView.rowHeight = 125;
    
    
    // 初始化服务类
    nls_ = [[NewsListService alloc]init];
    nls_.delegate = self;
    
    
    // 集成刷新控件
    [self setupRefresh];
    
    [_tableView headerBeginRefreshing];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 检查网络
    if (nls_.isQuery || ![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    nls_.pageInfo.pageno = @"1";
    [nls_ pageQueryWithSelectedIndex:selectedIndex];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    if (nls_.isQuery || !nls_.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        nls_.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [nls_.pageInfo nextPage];
    [nls_ pageQueryWithSelectedIndex:selectedIndex];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (nls_.pageInfo.dataArr.count != 0) {
        return nls_.pageInfo.dataArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"IPubCell";
    IPubHistoryTableViewCell *cell = (IPubHistoryTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"IPubHistoryTableViewCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (nls_.pageInfo.dataArr.count != 0) {
        cell.infoLbl.text = nls_.pageInfo.dataArr[indexPath.row][@"title"];
        cell.dateLbl.text = nls_.pageInfo.dataArr[indexPath.row][@"time"];
        
        [cell.deleteBtn addTarget:self action:@selector(deleteInformation:) forControlEvents:UIControlEventTouchUpInside];
        cell.deleteBtn.tag = indexPath.row;
    }
    
    return cell;
}

// 点击cell查看新闻详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YH_NewsDetailViewController *newsDetailVC = [[YH_NewsDetailViewController alloc]initWithNibName:@"YH_NewsDetailViewController" bundle:nil];
    newsDetailVC.newsId = nls_.pageInfo.dataArr[indexPath.row][@"id"];
    newsDetailVC.selectedIndex = selectedIndex;
    newsDetailVC.htmlStr = nls_.pageInfo.dataArr[indexPath.row][@"linkurl"];
    [self.navigationController pushViewController:newsDetailVC animated:YES];
}

// 删除信息
- (void)deleteInformation:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    UIButton *btn = (UIButton*)sender;
    btnTag = btn.tag;
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        
        /* 请求服务器删除对应类别下的信息 */
        
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            delRequest_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            delRequest_.requestMethod = @"POST";
            // 设置超时时间
            delRequest_.timeOutSeconds = 30;
            delRequest_.delegate = self;
            // 设置参数
            NSString *action;
            switch (selectedIndex) {
                case 0://新闻
                    action = @"newsdel";
                    break;
                case 1://人才
                    action = @"zhaopindel";
                    break;
                case 2://视频
                    action = @"videosdel";
                    break;
                case 3://产品
                    action = @"prosdel";
                    break;
                case 4://图片
                    action = @"casesdel";
                    break;
                case 5://服务
                    action = @"serinfordel";
                    break;
                default:
                    break;
            }
            //NSDictionary *paramsDict =  @{@"id": nls_.pageInfo.dataArr[btnTag][@"id"], @"uid": @"互联天下"};
            NSDictionary *paramsDict =  @{@"id": nls_.pageInfo.dataArr[btnTag][@"id"], @"uid": UNAME};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            delRequest_.postBody = [paramsData mutableCopy];
            
            [delRequest_ startAsynchronous];
        }
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [nls_.pageInfo.dataArr removeObjectAtIndex:btnTag];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btnTag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_tableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}


//返回
- (void)back {
    [nls_ cancelRequest];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
